package 接口测试;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;

public class NetworkClient {

    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final OkHttpClient client = new OkHttpClient();

    // 替换为你实际的 DHCCAM_URL
    private static final String DHCCAM_URL = "https://imh.dentalxjtu.com/dhccam/gateway/index";

    /**
     * 同步请求方法
     *
     * @param data   请求数据体
     * @param method 请求方法 (GET, POST)
     * @param url    请求地址
     * @return 响应数据中的 data 字段
     * @throws Exception 错误信息
     */
    public static JSONObject request(JSONObject data, String method, String url) throws Exception {
        if (url == null || url.isEmpty()) {
            url = DHCCAM_URL;
        }

        RequestBody body = RequestBody.create(data.toString(), JSON);
        Request.Builder requestBuilder = new Request.Builder().url(url);

        if ("POST".equalsIgnoreCase(method)) {
            requestBuilder.post(body);
        } else if ("GET".equalsIgnoreCase(method)) {
            requestBuilder.get();
        } else {
            throw new IllegalArgumentException("Unsupported HTTP method: " + method);
        }

        Request request = requestBuilder.build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response.code());
            }

            if (response.body() == null) {
                throw new IOException("Empty response body");
            }

            String responseBody = response.body().string();
            JSONObject jsonResponse = new JSONObject(responseBody);

            String code = jsonResponse.optString("code");
            String msg = jsonResponse.optString("msg", "Unknown error");

            if ("10000".equals(code)) {
                return jsonResponse.optJSONObject("data");
            } else {
                if ("50001".equals(code)) {
                    CacheHandler.removeToken();
                }
                ShowModel.showModel("提示", msg, false);
                throw new Exception(msg);
            }
        }
    }

    // 模拟 cacheHandler.removeToken()
    public static class CacheHandler {
        public static void removeToken() {
            System.out.println("Token removed.");
        }
    }

    // 模拟 showModel.showModel()
    public static class ShowModel {
        public static void showModel(String title, String message, boolean isCancelable) {
            System.out.println(title + ": " + message);
        }
    }
}